package models

import (
	"ginadmin/db"
	"github.com/jinzhu/gorm"
)

type Organization struct {
	gorm.Model
	Name       string
	ParentId   uint   //上级机构id
	ParentName string //上级机构名称
	Ancestors  string //1.11.72 上下级结构 --暂无作用。先赋值。以后可能会有业务使用
	OrderNum   int    //同级之间排序使用---暂时不使用
}

func (m *Organization) Add() error {
	err := new(error)
	DB := db.GetInstance().GetDB()
	if *err = DB.Create(m).Error; err != nil {
		return *err
	}
	return *err
}

func (m *Organization) Update(name string) error {
	err := new(error)
	DB := db.GetInstance().GetDB()
	if *err = DB.Model(m).Update("name", name).Error; err != nil {
		return *err
	}
	return *err
}

func List() (organizatList []Organization) {
	DB := db.GetInstance().GetDB()
	DB.Find(&organizatList)
	return
}

func FindOrgByParentId(parentId string) bool {
	DB := db.GetInstance().GetDB()
	DB = DB.Where("parent_id=?", parentId)
	result, _ := db.IsExit(DB, &Organization{})
	return result
}

func (org *Organization) FindOrgById(parentId string) bool {
	DB := db.GetInstance().GetDB()
	DB = DB.Where("id=?", parentId).Find(org)
	result, _ := db.IsExit(DB, &Organization{})
	return result
}

func (org *Organization) DelOrg() error {
	err := new(error)
	DB := db.GetInstance().GetDB()
	if *err = DB.Unscoped().Delete(org).Error; err != nil {
		return *err
	}
	return *err
}
